package com.boxedinsoftware.betamax.sms;



import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;



import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import de.ub0r.android.lib.apis.*;

public class BetamaxSMS extends BetamaxCheckLicence {
	
	protected String final_number;
	protected EditText number;
	protected EditText message;
	protected TextView message_info;
	protected TextView message_count_info;
	protected TextView accounts_count;
	protected RelativeLayout first;
	protected Button send;
	protected String country;
	AccountsSQLHelper dh;
	protected SharedPreferences preferences;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        
        this.dh = new AccountsSQLHelper(BetamaxSMS.this.getApplicationContext());
        refreshBalance();
        first = (RelativeLayout)findViewById(R.id.rl_l);
        LinearLayout stats = (LinearLayout)findViewById(R.id.statusLayout);
        if(preferences.getBoolean("statsShow", true) == true)
        {
        	
        	stats.setVisibility(View.VISIBLE);
        	
        }
        else
        {
        	
        	stats.setVisibility(View.GONE);
        	
        }
        if(preferences.getBoolean("autoFetch", true) == true)
        {
        	
        	TelephonyManager tMgr =(TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
			String sourceNumberString= tMgr.getLine1Number();
			SharedPreferences.Editor editor = preferences.edit();
		      editor.putString("ownNumber", sourceNumberString);
		      editor.commit();
        	
        }
        
        
        
        send = (Button)findViewById(R.id.send_);
        Button accounts = (Button)findViewById(R.id.accounts);
        Button cancel = (Button)findViewById(R.id.cancel);
        ImageButton select_contact = (ImageButton)findViewById(R.id.select_contact);
        
        final TextView x = (TextView)findViewById(R.id.country);
        number = (EditText)findViewById(R.id.number);
        number.setInputType(InputType.TYPE_CLASS_PHONE);
        number.setText(preferences.getString("draftNumber", ""));
        
        message = (EditText)findViewById(R.id.text);
        message.setText(preferences.getString("draftMessage", ""));
        
        
        message_info = (TextView)findViewById(R.id.text_char_count);
        message_count_info = (TextView)findViewById(R.id.text_messages_count);
        accounts_count = (TextView)findViewById(R.id.number_of_accounts);
        
        
        
        displayNumberOfAccounts(this.dh.getCount());
        
        
        accounts.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				BetamaxSMS.this.startActivity(new Intent(BetamaxSMS.this, AccountManager.class));
				
			}
        	
        	
        });
       
        send.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				if(number.getText().toString().startsWith("+") || number.getText().toString().startsWith("00"))
				{
				Intent i = new Intent(BetamaxSMS.this, SendSMS.class);
		     	i.putExtra("number", number.getText().toString());
		     	i.putExtra("message", message.getText().toString());
		     	i.putExtra("count", (message.getText().length() / 160) + 1);
		     	i.putExtra("country", country);
		     	
		     	SharedPreferences.Editor editor = preferences.edit();
		        editor.putString("draftNumber", number.getText().toString());
		        editor.putString("draftMessage", message.getText().toString());
		        editor.commit();
		     	
		     	BetamaxSMS.this.startActivity(i);
		   	    BetamaxSMS.this.finish();
				}
				else
				{
					
					Toast.makeText(BetamaxSMS.this, "Number not in international format Eg. +40766663264 or 00476663254", Toast.LENGTH_LONG).show();
					
					
				}
				
			}
        	
        });
        
        number.addTextChangedListener(new TextWatcher(){

			public void afterTextChanged(Editable s) {
				
				
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
				
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				
				
				country = CountryCodes.searchFor(number.getText().toString());
				x.setText(country);
				if(x.getText().toString().equalsIgnoreCase("Invalid Number")){
					x.setVisibility(8);
				
				}
				else
					x.setVisibility(0);
				
					if(number.getText().toString().startsWith("00")){
					
					number.setText("+" + number.getText().toString().substring(2));
					number.setSelection(number.getText().toString().length());
					
				}
				
			}
        	
        	
        	
        });
        
        try{
            String full_number = this.getIntent().getDataString();
            String numberzor = full_number.substring(full_number.indexOf(":") + 1, full_number.length());
    		final_number = numberzor.replaceAll("%2B", "+");
    		final_number = final_number.replaceAll( "-", "" );
            final_number = final_number.replace(")", "");
            final_number = final_number.replace("(", "");
            final_number = final_number.replaceAll(" ", "");
            final_number = final_number.replaceAll("[a-z,A-Z]", "");
            number.setText(final_number);
            
            }catch(Exception e){}
        
        
        message.addTextChangedListener(new TextWatcher(){

			public void afterTextChanged(Editable s) {
				
				
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
				
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				
				//, 
				try{
						displayCharStats(160 - (message.getText().length() % 160));
						displayMessagesStats((message.getText().length() / 160) + 1);
				}
				catch (Exception e)
				{
					displayCharStats(0);
					displayMessagesStats((message.getText().length() / 160) + 1);}
				
				
			}
        	
        	
        	
        });
        
       

        
        
        
        select_contact.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {  
            	
                	
                		BetamaxSMS.this.startActivityForResult(ContactsWrapper.getInstance().getPickPhoneIntent(), 23);
                	
            
            }});
        
        cancel.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				
				AlertDialog.Builder builder = new AlertDialog.Builder(BetamaxSMS.this);
				builder.setMessage("Are you sure you want to discard the message? ")
				       .setCancelable(false)
				       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				        	   SharedPreferences.Editor editor = preferences.edit();
						        editor.putString("draftNumber", "");
						        editor.putString("draftMessage", "");
						        editor.commit();
				                BetamaxSMS.this.finish();
				           }
				       })
				       .setNegativeButton("No", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                dialog.cancel();
				           }
				       });
				AlertDialog alert = builder.create();
				alert.show();
			}
        	
        	
        });
        
        try {
            //current version
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            int versionCode = packageInfo.versionCode; 

            //version where changelog has been viewed
            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
            int viewedChangelogVersion = settings.getInt("changeLogVersion", 0);

            if(viewedChangelogVersion<versionCode) {
                Editor editor=settings.edit();
                editor.putInt("changeLogVersion", versionCode);
                editor.commit();
                displayChangeLog();
            }
        } catch (NameNotFoundException e) {
            Log.w("Unable to get version code. Will not show changelog", e);
        }
        
    }
    
    
    @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data){
        super.onActivityResult(reqCode, resultCode, data);
     
        switch(reqCode){
           case (23):
             if (resultCode == Activity.RESULT_OK){
            	 final String phone = ContactsWrapper.getInstance().getNumber
					(this.getContentResolver(), data.getData());
            	 //Toast.makeText(this, phone, Toast.LENGTH_LONG).show();
            	 number.setText(phone);
            	 
            	break;
             }
        }
    }
    
    public void displayCharStats(int chars_left)
    {
    	
    	message_info.setText("(" + chars_left + "/" + "160" + ")");
    }
    
    public void displayMessagesStats(int messages)
    {
    	if(messages == 1)
    		message_count_info.setText("1 message");
    	else
    		message_count_info.setText("" + messages + " messages");
    }
    
    public void displayNumberOfAccounts(int number){
    	
    	if(number == 1){
    		accounts_count.setText("1 account");
    	}
    	else if(number == 0){
    		
    		accounts_count.setText("No accounts");
    		
    	}
    	else{
    		accounts_count.setText("" + number + " accounts");
    		
    	}
    	
    }


    
    @Override
    public void onResume()
    {
    	
    	displayNumberOfAccounts(this.dh.getCount());
    	LinearLayout stats = (LinearLayout)findViewById(R.id.statusLayout);
        if(preferences.getBoolean("statsShow", true) == true)
        {
        	
        	stats.setVisibility(View.VISIBLE);
        	
        }
        else
        {
        	
        	stats.setVisibility(View.GONE);
        	
        }
        if(preferences.getBoolean("autoFetch", true) == true)
        {
        	
        	TelephonyManager tMgr =(TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
			String sourceNumberString= tMgr.getLine1Number();
			SharedPreferences.Editor editor = preferences.edit();
		      editor.putString("ownNumber", sourceNumberString);
		      editor.commit();
        	
        }
    	super.onResume();
    	
    }
    
    
    public class refresh_balance extends AsyncTask<String, Void, String> {
    	
    	String[] params;
    	
    	@Override
    	protected String doInBackground(String... params) {
    		try{
        		
        		this.params = params;
				//Log.e("providerString", providerString);
				
				//Log.e("actualProvider", actualProvider);
				
			    HttpClient httpclient = new DefaultHttpClient();  
			    HttpGet httpget = new HttpGet("https://www."+params[1]+"/myaccount/getbalance.php?username="+params[2].trim()+"&password="+params[3].trim());
	            // Add your data  
	            
	      
	            // Execute HTTP Post Request  
	            HttpResponse response = httpclient.execute(httpget);  
	            
	            byte buffer[] = new byte[1024] ;
				InputStream is = response.getEntity().getContent() ;
				int numBytes = is.read(buffer) ;
				is.close();
				
				 String entityContents = new String(buffer,0,numBytes) ;
			    
					

					
		            
				 return entityContents;   
				}      
	         catch (ClientProtocolException e) { 
	        	Log.e("Betamax" , e.getMessage());
	        	return "error"; 
	        } catch (IOException e) {  
	        	Log.e("Betamax" , e.getMessage());
	        	return "error"; 
	        }
	        
    	
    	
    	
 }
    	
    	
    	
    	@Override
    	protected void onPostExecute(String result) {
    	
    		if(result.equalsIgnoreCase("error")){
    			Toast.makeText(BetamaxSMS.this, "Something went wrong. Please check your internet connection", Toast.LENGTH_LONG).show();
    		}
    		else{
    		params[4] = result;
    		try{
    		BetamaxSMS.this.dh.update( Double.parseDouble(params[4]),Integer.parseInt(params[0]));}
    		catch(Exception e){try{BetamaxSMS.this.dh.update( -1.0,Integer.parseInt(params[0]));}catch(Exception x){};}
    		}
    	}
    	
 }
 
 public void refreshBalance(){
     
     Cursor cursor = this.dh.selectAllForBalance();
        while (cursor.moveToNext()) {
            int ID = cursor.getInt(0);
            String provider = cursor.getString(1);
            String username = cursor.getString(2);
            String password = cursor.getString(3);
            String[] params = {"" + ID , provider, username, password , ""};
            new refresh_balance().execute(params);
          }

    }
 
 
 	public void support(){
 	
 	ComponentName comp = new ComponentName(BetamaxSMS.this, BetamaxSMS.class);
     PackageInfo pinfo = null;
		try {
			pinfo = BetamaxSMS.this.getPackageManager().getPackageInfo(comp.getPackageName(), 0);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		final String appVersion = pinfo.versionName;
 	
 	final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
     
     emailIntent.setType("plain/text");

     emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ "support@boxedinsoftware.com"});

     emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "[Support BetaMax SMS v" + appVersion +"]");

     BetamaxSMS.this.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
 	
 }
 
 	public void twitter(){
	   
	   Intent twitterIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://mobile.twitter.com/#!/BMAXSms")); 
	   startActivity(twitterIntent); 
	   
}


 	public void displayChangeLog()
{
	
	
	LayoutInflater li = LayoutInflater.from(this);
    View view = li.inflate(R.layout.changelog_view, null);
    TextView thankyou = (TextView)view.findViewById(R.id.thankyou);
    thankyou.setText(Html.fromHtml("Thank you for purchasing Betamax SMS with Rates" +
    				 " <br> Special thanks to <a href='market://search?q=pub:\"Felix Bechstein\"'>Felix Bechstein</a>"));
    new AlertDialog.Builder(this)
    .setTitle("Changelog")
    .setView(view)
    .setNegativeButton("Close", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
          dialog.dismiss();
      }
    })
    .show();
}
 
 
 	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	return true;
    }
    
   
    @Override 
    protected void onDestroy() {
          super.onDestroy();
          try{
          this.dh.stop();
          }catch(Exception e){}
    }
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// We have only one menu option
		case R.id.preferences:
			// Launch Preference activity
			Intent i = new Intent(BetamaxSMS.this, BetamaxSMSPrefs.class);
			startActivityForResult(i, 103);
			break;
		case R.id.support:
			support();
			break;
		case R.id.twitter:
			twitter();
			break;
		case R.id.changelog:
			displayChangeLog();
			break;

		}
		return true;
	}
    
}